package com.yujn.springsecurityactual.filter;

        import cn.hutool.core.util.StrUtil;
        import com.yujn.springsecurityactual.exception.VerCodeException;
        import com.yujn.springsecurityactual.bean.Final;
        import com.yujn.springsecurityactual.config.MyAuthenticationFailureHanler;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.security.core.AuthenticationException;
        import org.springframework.security.web.authentication.AuthenticationFailureHandler;
        import org.springframework.web.filter.OncePerRequestFilter;

        import javax.servlet.FilterChain;
        import javax.servlet.ServletException;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.servlet.http.HttpSession;
        import java.io.IOException;

/**
 * @description: 图形验证码过滤器
 * @author: Yujn
 * @create: 2021-03-22 20:38
 **/
public class VerificationCodeFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationFailureHandler myAuthenticationFailureHandler = new MyAuthenticationFailureHanler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            System.out.println("come in VericationCodeFilter");
            if ("/login".equals(httpServletRequest.getRequestURI())){
                // 校验验证码
//                this.verCode(httpServletRequest);
            }
            // 验证通过放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }catch (AuthenticationException e){
            // 用myAuthenticationFailureHandler响应错误的验证信息
            myAuthenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
        }
    }

    /**
     * 校验图形验证码
     * @param httpServletRequest
     * @return
     * @author yujn
     * @date 2021/3/22 21:25
     */
    private void verCode(HttpServletRequest httpServletRequest) {
        // 从request中获取用户输入的
        String code = httpServletRequest.getParameter(Final.CAPTCHA);
        // 从session中获取本次正确的验证码文本
        HttpSession session = httpServletRequest.getSession();
        String sessionCode = (String) session.getAttribute(Final.CAPTCHA);
        if (!StrUtil.isEmpty(sessionCode)){
            session.removeAttribute(Final.CAPTCHA);
        }
        if (StrUtil.isEmpty(sessionCode)
                || StrUtil.isEmpty(code)
                || !sessionCode.equals(code)){
            // 如果校验失败 则抛出自定义验证码校验失败异常
            throw new VerCodeException();
        }
    }
}
